<?php

namespace app\common\model;

use think\Model;
use think\Loader;
use think\Hook;
use think\Lang;
use Carbon\Carbon;
use think\Request;
use think\Exception;
use app\common\traits\model\TraitModel;
class Wishs extends Model
{
	use TraitModel;

    protected $resultSetType      = 'collection';
    protected $autoWriteTimestamp = 'timestamp';
    protected $createTime         = 'created_at';
    protected $updateTime         = 'updated_at';
    protected $table              = 'wishs';
    
    const POST_WISH_PRICE = 10;
	
	public function getRegionAttr($value){
		$status = [
			'Beijing'  => Lang::get('beijing'), 
    		'Shanghai' => Lang::get('shanghai'),
    		'Sanya'    => Lang::get('sanya'),
    		'Chengdu'  => Lang::get('chengdu'),
    		'Xian'     => Lang::get('xian')
		];
	   return $status[$value];
	}
	
    public function meetWishUsers()
    {
    	return $this->hasMany('MeetWishUsers', 'wish_id');
    }

    public function meets($wish_id = null)
    {
        $meet = Loader::model('MeetWishUsers');
        $meet->wish = $wish_id ? $this->getWishInfo(['id' => $wish_id, 'user_id' => Request::instance()->user->id]) : $this;
        return $meet;
    }

    /**
     * 获取心愿信息
     * @param  [type] $querys  [description]
     * @return [type]          [description]
     */
    public function getWishInfo($querys)
    {
    	if ($wish_info = $this->get($querys)) {
    		return $wish_info;
    	}
    	throw new Exception(Lang::get("Wish information does not exist"), 60001);    	
    }

    public function meetWish($caravan)
    {
    	//校验是否可以满足
    	if ($re = $caravan->checkCanPay($caravan->id, $this->start_date, $this->end_date)) {
	    	$this->meets()->meet($caravan);
            $wish_id = $this->id;
            //后置操作
            Hook::exec('app\\common\\behavior\\Wish','afterMeetWish', $wish_id); 

            return true; 
	    }
	    throw new Exception(Lang::get("Your car does not meet the conditions"), 60002); 
    }

    /**
     * 完成心愿
     * @param  [type] $meet_user_id [description]
     * @return [type]               [description]
     */
    public function completeWish($meet_id, $other)
    {
    	if ($this->complete_caravan_id) {
    		throw new Exception(Lang::get("Wish has been completed"), 60003);
    	}
    	
    	$meet_info = $this->meets()->getMeet($meet_id);

        $this->startTrans();
        try {
            $this->complete_caravan_id = $meet_id;
            $this->save();
            $id = $this->id;

            Loader::model('Capitals')->incIntegral($this->travel_coin, $meet_info->meet_user_id);
            Loader::model('Capitals')->reduceIntegral($this->travel_coin, $this->user_id);

            //生成订单
            $result = Loader::model('Users')->createOrder($meet_info->caravan_id, $this->start_date, $this->end_date, $other, false);

            $this->commit();
            
        } catch (\Exception $e) {
            $this->rollback();
            throw $e;
        }

    	//完成心愿后置操作
    	Hook::exec('app\\common\\behavior\\Wish','afterCompleteWish', $id);
		return $result;
    }

    /**
     * 修改心愿
     * @param  [type] $wish_id     [description]
     * @param  array  $update_info [description]
     * @return [type]              [description]
     */
    public function updateWish($wish_id, $update_info = [])
    {
    	if (empty($update_info['start_date']) || empty($update_info['end_date'])) {
            throw new Exception(Lang::get("The date can not be empty"), 60006);            
        }
		
    	$update_info['travel_coin']   = $update_info['travel_coin'] ? : 0;
        if (!is_numeric($update_info['travel_coin']) || $update_info['travel_coin'] < 0) {
            throw new Exception(Lang::get("Travel currency format error"), 60007);
        }
		
        $wish_info = $this->getWishInfo(['id' => $wish_id, 'user_id' => Request::instance()->user->id]);
		
    	if ($wish_info->complete_caravan_id) {
            throw new Exception(Lang::get("Wish has been completed"), 60003);
        }

        if ($wish_info->meetWishUsers()->count()) {
            throw new Exception("Wish someone has received orders, not allowed to modify", 60005);
        }

        $this->update($update_info, ['id' => $wish_id], true);
    }

    /**
     * 取消心愿
     * @return [type] [description]
     */
    public function cancelWishs()
    {
    	$this->meets()->delMeets();
        $this->delete();
    }

    /**
     * 获取心愿列表
     * @param  array  $querys [description]
     * @param  string $order  [description]
     * @return [type]         [description]
     */
    public function getWishs($querys = [], $order = 'id desc')
    {
        return $this->with('meetWishUsers')->where($querys)->order($order)->select();
    }
	/**
	 * 获取全部心愿列表
	 */
	public function getAllWishs($querys = [], $page, $order = 'id desc')
    {
        return $this->with('meetWishUsers')->where($querys)->order($order)->page($page,6)->select();
    }
	
    /**
     * 获取用户心愿列表
     * @return [type] [description]
     */
    public function getUserWishs($querys = [])
    {
    	return $this->getWishs(array_merge($querys, ['user_id' => Request::instance()->user->id]));
    }

    /**
     * 获取其他用户心愿
     * @return [type] [description]
     */
    public function getOtherUserWishs($where = [],$page)
    {
    	$now_date   = Carbon::now()->toDateString();
    	$base_where = [
    		'start_date'		  => ['EGT', $now_date],
    		'user_id'    		  => ['NEQ', Request::instance()->user->id], 
    		'region'   		      => ['EQ', Request::instance()->user->region],
    		'complete_caravan_id' => ['EQ', 0]
    	];

    	if ($where) {
    		if (array_key_exists('start_date', $where)) {
    			if ($this->comparisonDate($now_date, $where['start_date']) == 'gt') {
    				$where['start_date'] = $now_date;
    			}

    			if (array_key_exists('end_date', $where)) {
	    			if ($this->comparisonDate($where['start_date'], $where['end_date']) == 'gt') {
	    				$where['end_date'] = ['ELT', $where['start_date']];
	    			}else{
	    				$where['end_date'] = ['ELT', $where['end_date']];
	    			}
	    		}
	    		$where['start_date'] = ['EGT', $where['start_date']];
	    		$where = array_merge($base_where, $where);
    		}    		
    	}else{
    		$where = $base_where;
    	}
    	return $this->getAllWishs($where,$page);
    }

    /**
     * 创建用户心愿
     * @param  [type] $wish_infos [description]
     * @return [type]             [description]
     */
    public function createUserWishs($wish_infos)
    {
        if (empty($wish_infos['start_date']) || empty($wish_infos['end_date'])) {
            throw new Exception(Lang::get("The date can not be empty"), 60006);            
        }
		
        if (is_array($wish_infos) && key($wish_infos) !== 0) {
            $wish_infos = [$wish_infos];
        }

        $postwishprices = 0;

        foreach ($wish_infos as &$wish_info) {
            $wish_info['user_id'] = Request::instance()->user->id;
            $wish_info['travel_coin']   = $wish_info['travel_coin'] ? : 0;

            if (!is_numeric($wish_info['travel_coin']) || $wish_info['travel_coin'] < 0) {
                throw new Exception(Lang::get("Travel currency format error"), 60007);
            }

            $postwishprices += self::POST_WISH_PRICE;
        }

        $this->startTrans();
        try {
        	Loader::model('Capitals')->reduceIntegral($postwishprices, Request::instance()->user->id);
            $this->saveAll($wish_infos);
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw $e;
        }
        //后置操作
    	Hook::exec('app\\common\\behavior\\Wish','afterCreateUserWish', $wish_infos);     
    }
}
